import threading
import time

from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QPushButton, QComboBox, QHBoxLayout, QMessageBox

from src.python.func.fuhua_function import startFuhua
from src.python.tools.logHandler import logger
from src.python.tools.singleton import singleton

log = logger()


@singleton
class FuhuaPage(QWidget):

    def __init__(self):
        super().__init__()
        self.countdown_time = 0
        self.countdown_status = False
        self.fuhua_start_button_status = False
        self.interval = 31 * 60
        self.initUI()

    def initUI(self):
        # 创建分辨率选择栏
        self.resolution_select = QComboBox(self)
        self.resolution_select.addItem("请选择分辨率!!!")
        self.resolution_select.addItem("1920x1080")
        self.resolution_select.addItem("1680x1050")
        self.resolution_select.addItem("1024x768")
        self.resolution_select.addItem("800x600")

        # 创建一个水平布局来容纳文本和选择栏
        self.resolution_select_layout = QHBoxLayout()
        self.resolution_select_layout.setSpacing(5)
        self.resolution_select_layout.addWidget(QLabel("请先选择游戏分辨率:"))  # 添加文本标签
        self.resolution_select_layout.addWidget(self.resolution_select)  # 添加选择栏

        # 创建操作间隔选择栏
        self.click_interval_select = QComboBox(self)
        self.click_interval_select.addItem("0.5")
        self.click_interval_select.addItem("0.75")
        self.click_interval_select.addItem("1")
        self.click_interval_select.addItem("1.25")
        self.click_interval_select.addItem("1.5")
        self.click_interval_select.addItem("1.75")
        self.click_interval_select.addItem("2")

        # 创建一个水平布局来容纳文本和选择栏
        self.click_interval_select_layout = QHBoxLayout()
        self.click_interval_select_layout.setSpacing(5)
        self.click_interval_select_layout.addWidget(QLabel("请选择操作间隔(/秒):"))  # 添加文本标签
        self.click_interval_select_layout.addWidget(self.click_interval_select)  # 添加选择栏

        # 创建孵化页面的内容
        self.desc_label = QLabel("\n"
                                 "\n"
                                 "\n")

        # 创建倒计时
        self.countdown_label = QLabel("倒计时:0分0秒")

        # 创建孵化开始按钮
        self.fuhua_button = QPushButton("开始孵化", self)
        self.fuhua_button.setFixedSize(350, 50)
        self.fuhua_button.clicked.connect(self.fuhuaClick)

        # 创建孵化页面的垂直布局
        layout = QVBoxLayout()

        # 添加包含文本和选择栏的水平布局
        layout.addLayout(self.resolution_select_layout)
        layout.addLayout(self.click_interval_select_layout)
        layout.addWidget(self.desc_label)
        layout.addWidget(self.countdown_label)
        layout.addWidget(self.fuhua_button)

        self.setLayout(layout)

    def showNoSelectResolutionBox(self):
        log.warning("未选择分辨率")
        QMessageBox.information(self, '错误', '请选择游戏分辨率,否则无法识别坐标!', QMessageBox.Ok)

    def showNoFindWindowBox(self):
        log.warning("未找到游戏窗口")
        self.changeButtonText()
        self.changeCountdownStatus()
        QMessageBox.information(self, '错误', '未找到游戏窗口!', QMessageBox.Ok)

    def fuhuaClick(self):
        if not self.fuhua_start_button_status:
            if self.resolution_select.currentText() != "请选择分辨率!!!":
                log.info("开始孵化")
                self.changeButtonText()
                startFuhua("resolution_" + self.resolution_select.currentText())
            else:
                self.showNoSelectResolutionBox()
        elif self.fuhua_button.text() == "结束孵化":
            log.info("结束孵化")
            self.changeButtonText()
            try:
                self.fuhua_timer.cancel()
            except Exception as e:
                print(e)
            self.changeCountdownStatus()
            self.countDownLabelUpdate(0)

    def changeButtonText(self):
        if not self.fuhua_start_button_status:
            self.fuhua_button.setText("结束孵化")
            self.fuhua_start_button_status = True
        elif self.fuhua_start_button_status:
            self.fuhua_button.setText("开始孵化")
            self.fuhua_start_button_status = False

    def fuhuaTimerTask(self):
        self.changeCountdownStatus()
        self.fuhua_count_down()

        # 启动一个定时任务线程，每1秒执行一次孵化操作
        self.fuhua_timer = threading.Timer(self.interval, startFuhua,
                                           args=("resolution_" + self.resolution_select.currentText(),))
        self.fuhua_timer.daemon = True  # 设置为守护线程，程序退出时会自动结束
        self.fuhua_timer.start()
        log.info(f"创建孵化定时任务: {self.fuhua_timer}")

    def fuhuaCountDownTask(self):
        while self.countdown_status:
            if self.countdown_time <= 0:
                self.changeCountdownStatus()
            self.countDownLabelUpdate(self.countdown_time)
            self.countdown_time -= 1
            time.sleep(1)
        log.info(f"停止倒计时线程: {self.fuhua_count_down_thread}")

    def changeCountdownStatus(self):
        if self.countdown_status is True:
            self.countdown_status = False
        elif self.countdown_status is False:
            self.countdown_status = True

    def fuhua_count_down(self):
        self.countdown_time = self.interval
        self.fuhua_count_down_thread = threading.Thread(target=self.fuhuaCountDownTask, name="倒计时线程")
        self.fuhua_count_down_thread.daemon = True
        self.fuhua_count_down_thread.start()
        log.info(f"创建倒计时线程: {self.fuhua_count_down_thread}")

    def countDownLabelUpdate(self, t):
        self.countdown_time = t
        self.countdown_label.setText(f"倒计时:{int(self.countdown_time / 60)}分{self.countdown_time % 60}秒")

    def get_click_interval(self):
        return float(self.click_interval_select.currentText())
